package com.hundun.hddeal.service.lmpl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hundun.hddeal.dao.GzhMapper;
import com.hundun.hddeal.entity.Gzh;
import com.hundun.hddeal.entity.GzhBody;
import com.hundun.hddeal.entity.GzhCount;
import com.hundun.hddeal.response.Result;
import com.hundun.hddeal.response.ResultUtil;
import com.hundun.hddeal.service.GzhService;
import com.hundun.hddeal.util.MD5Util;
import com.hundun.hddeal.vo.GzhVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

import static org.assertj.core.util.DateUtil.now;
/**
 * 公众号业务层
 * @author 谢
 */
@Service
public class GzhServiceImpl implements GzhService {

    @Autowired
    GzhMapper gzhMapper;



    /**
     * 通过类别Id查询gzh
     *
     * @param
     * @return
     */
    @Override
    public PageInfo<Gzh> selectByMtIdAndState(Integer page,Integer size,Long mtId) {
        //开启分页查询，写在查询语句上方
        //只有紧跟在PageHelper.startPage方法后的第一个Mybatis的查询（Select）方法会被分页。
        PageHelper.startPage(page, size);
        List<Gzh> gzhList = gzhMapper.selectMtId(mtId);
        PageInfo<Gzh> pageInfo = new PageInfo<>(gzhList);
        return pageInfo;
    }

    /**
     * 通过用户Id 查找所有公众号
     * @param page
     * @param size
     * @param
     * @return
     */
    @Override
    public PageInfo<GzhBody> selectByMtId(Integer page, Integer size, String mtId,
                                      Byte status,String gzhName,Double gzhSex,
                                      List typeName,String cityOne,Integer gzhType,
                                      Double readOne,Double readTwo,Integer fans,
                                          Double scoreOne,Double scoreTwo,String ghId,String admin,Integer failureCookie){
        Base64.Decoder decoder = Base64.getDecoder();
        //开启分页查询，写在查询语句上方
        //只有紧跟在PageHelper.startPage方法后的第一个Mybatis的查询（Select）方法会被分页。
        PageHelper.startPage(page, size);
        List<GzhBody> gzhList = gzhMapper.selectByMtId(mtId,status,gzhName,gzhSex,typeName,cityOne,gzhType,readOne,
                readTwo,fans,scoreOne,scoreTwo,ghId,admin,failureCookie);
        for (GzhBody gzh:gzhList) {
            if(gzh.getGzhIntro()!=null){
                gzh.setGzhIntro(new String(decoder.decode(gzh.getGzhIntro()), StandardCharsets.UTF_8));
            }
            if(gzh.getGzhPwd()!=null){
                try {
                    gzh.setGzhPwd(MD5Util.MD(gzh.getGzhPwd()));
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }

        }
        PageInfo<GzhBody> pageInfo = new PageInfo<>(gzhList);
        return pageInfo;
    }


    @Override
    public List<Gzh> selectMtId(Long mtId) {
        try {
            List<Gzh> gzhList = gzhMapper.selectMtId(mtId);
            if (gzhList!= null){
                gzhList = new ArrayList<>();
            }
            return gzhList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
    /**
     * 增加Gzh
     * @param record
     * @return
     */
    @Override
    public Result<Gzh> addGzh(Gzh record) {
        try {
            Gzh gzh =gzhMapper.selectByGhId(record.getGhId());
            if (gzh!=null) {
                return ResultUtil.error(200,"公众号已存在");
            }
            gzhMapper.insertSelective(record);
            return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error();
        }
    }



    /**
     * 更新Gzh
     * @param record
     * @return
     */
    @Override
    public Result<Gzh> updateGzh(GzhVo record) {
        try {
            Gzh gzh=gzhMapper.selectById(record.getId());
                gzh.setGhId(record.getGhId());
                gzh.setGzhName(record.getGzhName());
                gzh.setGzhUrl(record.getGzhUrl());
                gzh.setGzhLogo(record.getGzhLogo());
                gzh.setGzhCode(record.getGzhCode());
                gzh.setGzhFans(record.getGzhFans());
                gzh.setFansPic(record.getFansPic());
                Base64.Encoder encoder = Base64.getEncoder();
                byte[] textByte = record.getGzhIntro().getBytes(StandardCharsets.UTF_8);
                String encodedText = encoder.encodeToString(textByte);
                gzh.setGzhIntro(encodedText);
                gzh.setPriceFirst(record.getPriceFirst());
                gzh.setPriceSecond(record.getPriceSecond());
                gzh.setPriceOne(record.getPriceSecond());
                gzh.setTypeName(record.getTypeName());
                gzh.setGzhAge(record.getGzhAge());
                gzh.setGzhSex(record.getGzhSex());
                gzh.setGzhPrice(record.getGzhPrice());
                gzh.setFansType(record.getFansType());
                gzh.setCityOne(record.getCityOne());
                gzh.setCityTwo(record.getCityTwo());
                gzh.setCityThree(record.getCityThree());
                gzh.setCityPic(record.getCityPic());
                gzh.setReadNum(record.getReadNum());
                gzh.setAdmin(record.getAdmin());
                gzh.setAdminPhone(record.getAdminPhone());
                gzh.setUpdateDate(now());
                gzh.setGzhPwd(record.getGzhPwd());
                gzhMapper.updateGzh(gzh);
                return ResultUtil.success();

        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultUtil.error();
    }

    /**
     * 删除Gzh
     * @param record
     * @return
     */
    @Override
    public Result<Gzh> deleteGzh(Gzh record) {
        try{
            if (record == null) {
                return ResultUtil.ISNULL(record);
            }
            gzhMapper.deleteByGhId(record.getGhId());
            return ResultUtil.success("删除成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultUtil.error();
    }

    /**
     * 商场展示公众号
     * @param page
     * @param size
     * @param
     * @return
     */
    @Override
    public PageInfo<GzhBody> selectAllGzh(Integer page, Integer size,List typeName,Integer gzhAge,Double gzhSex,Integer gzhPrice,
                                          Integer fansType, Integer readNum,String cityOne,Byte status,String gzhName,String ghId,
                                          Integer gzhType,Integer sort,Double score){
        Base64.Decoder decoder = Base64.getDecoder();

        if(gzhSex==null){
            gzhSex=null;
            //男性居多
        }else if(gzhSex==1){
            gzhSex=0.5;
            //女性居多
        }else if(gzhSex==2){
            gzhSex=0.6;
            //泛性别
        }else if(gzhSex==3){
            gzhSex=0.7;
        }

        //开启分页查询，写在查询语句上方
        //只有紧跟在PageHelper.startPage方法后的第一个Mybatis的查询（Select）方法会被分页。
        PageHelper.startPage(page, size);
        List<GzhBody> gzhList = gzhMapper.findByGzh(typeName,gzhAge,gzhSex,gzhPrice,fansType,readNum,cityOne,status,gzhName,ghId,gzhType,sort,score);
        for(int i=0;i<gzhList.size();i++){
            //计算头条单价
            Double one=gzhList.get(i).getPriceFirst();
            if(gzhList.get(i).getReadnumAv()!=null && gzhList.get(i).getReadnumAv()!=0.0){
                BigDecimal b =new BigDecimal(one/gzhList.get(i).getReadnumAv());
                gzhList.get(i).setReadOnePrice(b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
            }else {
                gzhList.get(i).setReadOnePrice(0.00);
            }
            //计算非头条单价
            Double two=gzhList.get(i).getPriceSecond();
            if(gzhList.get(i).getNreadnumAv()!=null && gzhList.get(i).getNreadnumAv()!=0.0){
                BigDecimal b =new BigDecimal(two/gzhList.get(i).getNreadnumAv());
                gzhList.get(i).setReadSecondPrice(b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
            }else {
                gzhList.get(i).setReadSecondPrice(0.00);
            }
               //base64解码
            if(gzhList.get(i).getGzhIntro()!=null){
                gzhList.get(i).setGzhIntro(new String(decoder.decode(gzhList.get(i).getGzhIntro()), StandardCharsets.UTF_8));
            }


        }
        PageInfo<GzhBody> pageInfo = new PageInfo<>(gzhList);
        return pageInfo;
    }



    @Override
    public Result<GzhBody> selectGzhBody(String ghId) {
        try{
            Base64.Decoder decoder = Base64.getDecoder();
            GzhBody  gzhBody=gzhMapper.selectGzhBody(ghId);
            if(gzhBody.getGzhIntro()!=null){
                gzhBody.setGzhIntro(new String(decoder.decode(gzhBody.getGzhIntro()), StandardCharsets.UTF_8));
            }
            return ResultUtil.success(gzhBody);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error();
        }

    }


    @Override
    public Result<GzhBody> selectByPrimaryKey(String ghId) {
        try{
            Base64.Decoder decoder = Base64.getDecoder();
            GzhBody gzh =gzhMapper.selectByPrimaryKey(ghId);
            if(gzh.getGzhIntro()!=null){
                gzh.setGzhIntro(new String(decoder.decode(gzh.getGzhIntro()), StandardCharsets.UTF_8));
            }
            return ResultUtil.success(gzh);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error();
        }

    }

    @Override
    public Result getGzhCount(String mtId) {
        try{
            GzhCount count=gzhMapper.getGzhCount(mtId);
            return ResultUtil.success(count);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error();
        }
    }
}
